<template>
	<com-popup-new ref="popup" :action="props.action" :title="props.title || titleObj[props.mode]" @close="emits('close')" @submit="submitFn">
		<picker-view :immediate-change="true" class="gy-picker-view" indicator-style="height: 50px;" :value="defaultValue" @change="bindChangeFn">
			<picker-view-column v-for="(option,index) in options" :key="index">
				<view class="gy-picker-view-item" v-for="item in option" :key="JSON.stringify(item)">{{ item.label }}</view>
			</picker-view-column>
		</picker-view>
	</com-popup-new>
</template>

<script lang="ts" setup>

	import {
		ref,
		onMounted
	} from "vue";

    const emits = defineEmits(["submit", "update:modelValue", "close"]);

    const props = defineProps({
    	modelValue: {
    		type: String
    	},
    	title: {
    		type: String
    	},
    	mode: {
    		type: String,
    		default: "custom"
    	},
    	type: {
    		type: String
    	},
    	dateTimeFormat: {
    		type: String,
    		default: "yyyy-MM-dd HH:mm:ss"
    	},
    	startDateTime: {
    		type: String,
    		default: "1970/01/01 00:00:00"
    	},
    	endDateTime: {
    		type: String,
    		default: "2099/12/31 00:00:00"
    	},
    	option: {
    		type: Array,
    		default: () => [] as any
    	},
    	btnText: {
    		type: String,
    		default: "确 认"
    	},
			action: {
    		type: Boolean,
    		default: false
    	},
    });

	const region = [];
	const nation = [];

    const popup: any = ref(null);
    const defaultValue: any = ref([]);
    const options: any = ref([]);
    const titleObj = ref({
        "datetime": "日期时间选择",
        "region": "地区选择",
        "nation": "民族选择",
        "custom": "自定义单列选择",
        "custom-interlock": "自定义层级联动选择"
    });

    function bindChangeFn(e: any){
    	defaultValue.value = e.detail.value;
    	if(props.mode === "datetime"){
    		let str = "";
    		if(props.dateTimeFormat.startsWith("yyyy")){
    			str += options.value[0][e.detail.value[0]].value;
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM")){
    			str += "/" + options.value[1][e.detail.value[1]].value;
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM-dd")){
    			str += "/" + options.value[2][e.detail.value[2]].value;
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM-dd HH")){
    			str += " " + options.value[3][e.detail.value[3]].value;
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM-dd HH:mm")){
    			str += ":" + options.value[4][e.detail.value[4]].value;
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM-dd HH:mm:ss")){
    			str += ":" + options.value[5][e.detail.value[5]].value;
    		}
    		if(props.dateTimeFormat.startsWith("HH")){
    			str += options.value[0][e.detail.value[0]].value;
    		}
    		if(props.dateTimeFormat.startsWith("HH:mm")){
    			str += ":" + options.value[1][e.detail.value[1]].value;
    		}
    		if(props.dateTimeFormat.startsWith("HH:mm:ss")){
    			str += ":" + options.value[2][e.detail.value[2]].value;
    		}
    		setDateTimeOptionFn(str);
    	}else if(props.mode === "region" || props.mode === "custom-interlock"){
    		setInterlockOptionFn(e.detail.value);
    	}
    }

    function setOptionsFn(){
    	if(props.mode === "custom"){
    		options.value = [props.option]
    	} else if(props.mode === "nation"){
    		options.value = nation;
    	} else if(props.mode === "region" || props.mode === "custom-interlock"){
    		let arr = props.modelValue ? props.modelValue.split("/") : [];
    		let valueArr: any = [];
    		let option: any = props.mode === "region" ? region : props.option;
    		arr.forEach((item,index) => {
    			if(index === 0){
    				valueArr.push(findIndexFn(option, item, "label"));
    			}else if(index === 1){
    				valueArr.push(findIndexFn(option[valueArr[0]].children, item, "label"));
    			}else if(index === 2){
    				valueArr.push(findIndexFn(option[valueArr[0]].children[valueArr[1]].children, item, "label"));
    			}
    		})
    		setInterlockOptionFn(valueArr);
    	} else if(props.mode === "datetime"){
    		setDateTimeOptionFn(props.modelValue);
    	}
    }
    function setValueFn(){
    	defaultValue.value = [];
    	if(props.mode === "datetime"){
    		let defaultDateTime: any = dateInitFn(props.modelValue);
    		let arr: any = [];
    		if(props.dateTimeFormat.startsWith("yyyy")){
    			arr.push(defaultDateTime.year);
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM")){
    			arr.push(defaultDateTime.month);
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM-dd")){
    			arr.push(defaultDateTime.date);
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM-dd HH")){
    			arr.push(defaultDateTime.hours);
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM-dd HH:mm")){
    			arr.push(defaultDateTime.minutes);
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM-dd HH:mm:ss")){
    			arr.push(defaultDateTime.seconds);
    		}
    		if(props.dateTimeFormat.startsWith("HH")){
    			arr.push(defaultDateTime.hours);
    		}
    		if(props.dateTimeFormat.startsWith("HH:mm")){
    			arr.push(defaultDateTime.minutes);
    		}
    		if(props.dateTimeFormat.startsWith("HH:mm:ss")){
    			arr.push(defaultDateTime.seconds);
    		}
    		arr.forEach((item: any, index: number) => {
    			defaultValue.value.push(findIndexFn(options.value[index], item, "value"))
    		})
    	} else if(props.mode === "region" || props.mode === "custom-interlock"){
    		let arr: any = props.modelValue ? props.modelValue.split("/") : [];
    		if(arr.length == 0){
    			defaultValue.value = [0,0,0];
    		}
    		if(arr.length >= 1){
    			defaultValue.value.push(findIndexFn(options.value[0], arr[0], "label"));
    		}
    		if(arr.length >= 2){
    			defaultValue.value.push(findIndexFn(options.value[1], arr[1], "label"));
    		}
    		if(arr.length === 3){
    			defaultValue.value.push(findIndexFn(options.value[2], arr[2], "label"));
    		}
    	} else if(props.mode === "nation"){
    		defaultValue.value.push(findIndexFn(nation[0], props.modelValue, "value"));
    	} else {
    		defaultValue.value = [findIndexFn(options.value[0], props.modelValue, "value")]
    	}
    }
    function setInterlockOptionFn(valueArr: any){
    	let option: any = props.mode === "region" ? region : props.option;
    	let arr = [option];
    	let index1 = 0;
    	let index2 = 0;
    	if(valueArr.length > 0){
    		index1 = valueArr[0];
    		index2 = valueArr[1];
    	}
    	arr.push(option[index1].children);
    	arr.push(option[index1].children[index2].children);
    	options.value = arr;
    }
    function setDateTimeOptionFn(defaultDate: any){
    	let startDateTime = dateInitFn(props.startDateTime);
    	let endDateTime = dateInitFn(props.endDateTime);
    	let defaultDateTime = dateInitFn(defaultDate);
    	let arr: any = [];
    	if(props.dateTimeFormat.startsWith("yyyy")){
    		arr.push(makeDateTimeFn(startDateTime.year || 1970, endDateTime.year || 2099, "年"));
    	}
    	if(props.dateTimeFormat.startsWith("yyyy-MM")){
    		let start = startDateTime.month && startDateTime.year === defaultDateTime.year ? startDateTime.month : 1;
    		let end = endDateTime.month && endDateTime.year === defaultDateTime.year ? endDateTime.month : 12;
    		arr.push(makeDateTimeFn(start, end, "月"));
    	}
    	if(props.dateTimeFormat.startsWith("yyyy-MM-dd")){
    		arr.push(makeDateTimeFn((defaultValue.value[0] === 0 && defaultValue.value[1] === 0) || unionFn([
                startDateTime.date,
                startDateTime.year === defaultDateTime.year,
                startDateTime.month === defaultDateTime.month
            ]) ? startDateTime.date : 1, unionFn([
                endDateTime.date,
                endDateTime.year === defaultDateTime.year,
                endDateTime.month === defaultDateTime.month
            ]) ? endDateTime.date : getMonthDaysFn(defaultDateTime.year, defaultDateTime.month), "日"));
    	}
    	if(props.dateTimeFormat.startsWith("yyyy-MM-dd HH")){
    		arr.push(makeDateTimeFn(unionFn([
                startDateTime.hours,
                startDateTime.year === defaultDateTime.year,
                startDateTime.month === defaultDateTime.month,
                startDateTime.date === defaultDateTime.date
            ]) ? startDateTime.hours : 0, unionFn([
                endDateTime.hours,
                endDateTime.year === defaultDateTime.year,
                endDateTime.month === defaultDateTime.month,
                endDateTime.date === defaultDateTime.date
            ]) ? endDateTime.hours : 23, "时"));
    	}
    	if(props.dateTimeFormat.startsWith("yyyy-MM-dd HH:mm")){
    		arr.push(makeDateTimeFn(unionFn([
                startDateTime.minutes,
                startDateTime.year === defaultDateTime.year,
                startDateTime.month === defaultDateTime.month,
                startDateTime.date === defaultDateTime.date,
                startDateTime.hours === defaultDateTime.hours
            ]) ? startDateTime.minutes : 0, unionFn([
                endDateTime.minutes,
                endDateTime.year === defaultDateTime.year,
                endDateTime.month === defaultDateTime.month,
                endDateTime.date === defaultDateTime.date,
                endDateTime.hours === defaultDateTime.hours
            ]) ? endDateTime.minutes : 59, "分"));
    	}
    	if(props.dateTimeFormat.startsWith("yyyy-MM-dd HH:mm:ss")){
    		arr.push(makeDateTimeFn(unionFn([
                startDateTime.seconds,
                startDateTime.year === defaultDateTime.year,
                startDateTime.month === defaultDateTime.month,
                startDateTime.date === defaultDateTime.date,
                startDateTime.hours === defaultDateTime.hours,
                startDateTime.minutes === defaultDateTime.minutes
            ]) ? startDateTime.seconds : 0, unionFn([
                endDateTime.seconds,
                endDateTime.year === defaultDateTime.year,
                endDateTime.month === defaultDateTime.month,
                endDateTime.date === defaultDateTime.date,
                endDateTime.hours === defaultDateTime.hours,
                endDateTime.minutes === defaultDateTime.minutes
            ]) ? endDateTime.seconds : 59, "秒"));
    	}
    	if(props.dateTimeFormat.startsWith("HH")){
    		arr.push(makeDateTimeFn(unionFn([
                startDateTime.hours,
                startDateTime.year === defaultDateTime.year,
                startDateTime.month === defaultDateTime.month,
                startDateTime.date === defaultDateTime.date
            ]) ? startDateTime.hours : 0, unionFn([
                endDateTime.hours,
                endDateTime.year === defaultDateTime.year,
                endDateTime.month === defaultDateTime.month,
                endDateTime.date === defaultDateTime.date
            ]) ? endDateTime.hours : 23, "时"));
    	}
    	if(props.dateTimeFormat.startsWith("HH:mm")){
    		arr.push(makeDateTimeFn(unionFn([
                startDateTime.minutes,
                startDateTime.year === defaultDateTime.year,
                startDateTime.month === defaultDateTime.month,
                startDateTime.date === defaultDateTime.date,
                startDateTime.hours === defaultDateTime.hours
            ]) ? startDateTime.minutes : 0, unionFn([
                endDateTime.minutes,
                endDateTime.year === defaultDateTime.year,
                endDateTime.month === defaultDateTime.month,
                endDateTime.date === defaultDateTime.date,
                endDateTime.hours === defaultDateTime.hours
            ]) ? endDateTime.minutes : 59, "分"));
    	}
    	if(props.dateTimeFormat.startsWith("HH:mm:ss")){
    		arr.push(makeDateTimeFn(unionFn([
                startDateTime.seconds,
                startDateTime.year === defaultDateTime.year,
                startDateTime.month === defaultDateTime.month,
                startDateTime.date === defaultDateTime.date,
                startDateTime.hours === defaultDateTime.hours,
                startDateTime.minutes === defaultDateTime.minutes
            ]) ? startDateTime.seconds : 0, unionFn([
                endDateTime.seconds,
                endDateTime.year === defaultDateTime.year,
                endDateTime.month === defaultDateTime.month,
                endDateTime.date === defaultDateTime.date,
                endDateTime.hours === defaultDateTime.hours,
                endDateTime.minutes === defaultDateTime.minutes
            ]) ? endDateTime.seconds : 59, "秒"));
    	}
    	options.value = arr;
    }
    function makeDateTimeFn(start: number, end: number, unit: string){
    	let arr: any = [];
    	for (let i = start; i <= end; i++) {
    		arr.push({
    			label: i + unit,
    			value: i
    		});
    	}
    	return arr;
    }
    function submitFn(){
    	let arr: any = [];
    	defaultValue.value.forEach((item: any,index: number) => {
    		if(options.value[index] && options.value[index][item]){
    			arr.push(options.value[index][item])
    		}
    	})
    	let val: any = [];
    	arr.forEach((item: any) => {
    		val.push(item[props.mode === "datetime" ? "value" : "label"])
    	})
    	if(props.mode === "nation" || props.mode === "region" || props.mode === "custom-interlock"){
    		// emits("submit", val.join("/"), arr);
    	} else if(props.mode === "datetime"){
    		let str = "";
    		if(props.dateTimeFormat.startsWith("yyyy")){
    			str += val[0];
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM")){
    			str += "-" + (Number(val[1]) < 10 ? ('0' + val[1]) : val[1]);
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM-dd")){
    			str += "-" + (Number(val[2]) < 10 ? ('0' + val[2]) : val[2]);
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM-dd HH")){
    			str += " " + (Number(val[3]) < 10 ? ('0' + val[3]) : val[3]);
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM-dd HH:mm")){
    			str += ":" + (Number(val[4]) < 10 ? ('0' + val[4]) : val[4]);
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM-dd HH:mm:ss")){
    			str += ":" + (Number(val[5]) < 10 ? ('0' + val[5]) : val[5]);
    		}
    		if(props.dateTimeFormat.startsWith("HH")){
    			str += (Number(val[0]) < 10 ? ('0' + val[0]) : val[0]);
    		}
    		if(props.dateTimeFormat.startsWith("HH:mm")){
    			str += ":" + (Number(val[1]) < 10 ? ('0' + val[1]) : val[1]);
    		}
    		if(props.dateTimeFormat.startsWith("HH:mm:ss")){
    			str += ":" + (Number(val[2]) < 10 ? ('0' + val[2]) : val[2]);
    		}
    		emits("update:modelValue", str);
				console.log('laizhelema', str);
				
    		// emits("submit", str, arr);
    	}else{
    		emits("update:modelValue", arr[0].value);
    		// emits("submit", val.join("/"), arr);
    	}
    	closeFn();
    }
    function closeFn() {
    	popup.value?.closeFn();
		emits("close");
    }
    function findIndexFn(arr: Array<any>, val: any, key: any){
    	for (let i = 0; i < arr.length; i++) {
    		if(val === arr[i][key]){
    			return i;
    		}
    	}
    	return 0
    }
    function dateInitFn(val: any){
    	if(val){
    		let re = new RegExp("-", "gi");
    		let str = val.replace(re, "/");
    		let arr: any = [];
    		if(props.dateTimeFormat.startsWith("yyyy")){
    			try{
    				arr.push(str.split(" ")[0].split("/")[0])
    			}catch{
    				arr.push(0);
    			}
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM")){
    			try{
    				arr.push(str.split(" ")[0].split("/")[1])
    			}catch{
    				arr.push(0);
    			}
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM-dd")){
    			try{
    				arr.push(str.split(" ")[0].split("/")[2])
    			}catch{
    				arr.push(0);
    			}
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM-dd HH")){
    			try{
    				arr.push(str.split(" ")[1].split(":")[0])
    			}catch{
    				arr.push(0);
    			}
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM-dd HH:mm")){
    			try{
    				arr.push(str.split(" ")[1].split(":")[1])
    			}catch{
    				arr.push(0);
    			}
    		}
    		if(props.dateTimeFormat.startsWith("yyyy-MM-dd HH:mm:ss")){
    			try{
    				arr.push(str.split(" ")[1].split(":")[2])
    			}catch{
    				arr.push(0);
    			}
    		}
    		return {
    			year: arr[0] && arr[0] !== "00" ? Number(arr[0]) : 0,
    			month: arr[1] && arr[1] !== "00" ? Number(arr[1]) : 0,
    			date: arr[2] && arr[2] !== "00" ? Number(arr[2]) : 0,
    			hours: arr[3] && arr[3] !== "00" ? Number(arr[3]) : 0,
    			minutes: arr[4] && arr[4] !== "00" ? Number(arr[4]) : 0,
    			seconds: arr[5] && arr[5] !== "00" ? Number(arr[5]) : 0
    		}
    	}else{
    		let initDate = new Date();
    		return {
    			year: initDate.getFullYear(),
    			month: initDate.getMonth() + 1,
    			date: initDate.getDate(),
    			hours: initDate.getHours(),
    			minutes: initDate.getMinutes(),
    			seconds: initDate.getSeconds()
    		}
    	}
    }
    function unionFn(arr: any): Boolean{
        for (let i = 0; i < arr.length; i++) {
            if(!arr[i]){
                return false;
            }
        }
        return true;
    }
    function getMonthDaysFn(year: string | number, month: string | number){
    	let y = Number(year)
    	let m = Number(month)
    	let day30 = [4,6,9,11]
    	let day31 = [1,3,5,7,8,10,12]
    	for (var i = 0; i < day30.length; i++) {
    		if(day30[i] === m){
    			return 30
    		}
    	}
    	for (var i = 0; i < day31.length; i++) {
    		if(day31[i] === m){
    			return 31
    		}
    	}
    	if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) {
    	    return 29
    	} else {
    	    return 28
    	}
    }

    onMounted(() => {
        setOptionsFn();
        setValueFn();
    });

</script>

<style lang="scss" scoped>
	.gy-picker-view {
	    width: 100%;
	    height: 500rpx;
	    .gy-picker-view-item {
	        height: 100rpx;
	        @include flex-center-center;
	        font-size: var(--gy-font-size-medium);
	    }
	}

</style>
